package mercadologico.gui.marca;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import mercadologico.action.MarcaActionManager;
import mercadologico.entities.tables.Marca;
import exceptions.PersistenceExceptionMessage;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

@SuppressWarnings("serial")
public class MarcaPesquisa extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField txtDescricao;
	private JScrollPane scrollPane;
	private JTable table;
	private JButton btnPesquisar;
	private JButton btnSelecionar;
	private JButton btnSair;
	
	private Marca marca;
	
	private MarcaActionManager action;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			MarcaPesquisa dialog = new MarcaPesquisa();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public MarcaPesquisa() {
		setModal(true);
		setResizable(false);
		setTitle("Pesquisa de Marca");
		setBounds(100, 100, 415, 350);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		JLabel lblDescrio = new JLabel("Descri\u00E7\u00E3o");
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "Resultado da Pesquisa", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
		gl_contentPanel.setHorizontalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addContainerGap()
							.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
								.addComponent(panel, GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
								.addGroup(gl_contentPanel.createSequentialGroup()
									.addComponent(getTxtDescricao(), GroupLayout.PREFERRED_SIZE, 273, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(getBtnPesquisar()))
								.addComponent(lblDescrio)))
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addGap(108)
							.addComponent(getBtnSelecionar())
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(getBtnSair(), GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		gl_contentPanel.setVerticalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addContainerGap()
					.addComponent(lblDescrio)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(getTxtDescricao(), GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
						.addComponent(getBtnPesquisar()))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(getBtnSelecionar())
						.addComponent(getBtnSair()))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addComponent(getScrollPane(), GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addComponent(getScrollPane(), GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
		);
		panel.setLayout(gl_panel);
		contentPanel.setLayout(gl_contentPanel);
	}
	
	public JTextField getTxtDescricao() {
		if (txtDescricao == null) {
			txtDescricao = new JTextField();
			txtDescricao = new JTextField();
			txtDescricao.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyChar() == KeyEvent.VK_ENTER || arg0.getKeyCode() == 40)
						getBtnPesquisar().requestFocus();
				}
			});
			txtDescricao.setColumns(10);
		}
		return txtDescricao;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table == null) {
			table = new JTable();
			table.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 39)
						getBtnSelecionar().requestFocus();
					if (e.getKeyCode() == 37)
						getBtnPesquisar().requestFocus();
				}
			});
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (arg0.getClickCount() == 2) {
						setMarca(getObjectSelecionado());
						if (getMarca() != null)
							dispose();
					}
				}
			});
			table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			table.setModel(new DefaultTableModel(
					createLinhas(),
				new String[] {
					"Descri\u00E7\u00E3o"
				}
			) {
				boolean[] columnEditables = new boolean[] {
					false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			table.getColumnModel().getColumn(0).setResizable(false);
			table.getColumnModel().getColumn(0).setPreferredWidth(80);
			table.getColumnModel().getColumn(0).setMinWidth(80);
			table.getColumnModel().getColumn(0).setMaxWidth(600);
			table.setFillsViewportHeight(true);
		}
		return table;
	}
	private Marca getObjectSelecionado() {
		int linha = getTable().getSelectedRow();
		if (linha >= 0) {
			return (Marca) getTable().getValueAt(linha, 0);
		}
		return null;
	}

	private Object[][] createLinhas() {
		try {
			ArrayList<Marca> marcas = getAction().findAll();
			Collections.sort(marcas);
			Object[][] linhas = new Object[marcas.size()][1];
			int cont = 0;
			for (Marca marca : marcas) {
				linhas[cont][0] = marca;
				cont++;
			}
			return linhas;
		} catch (PersistenceExceptionMessage e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public MarcaActionManager getAction() {
		if (action == null) {
			action = new MarcaActionManager();
		}
		return action;
	}

	public Marca getMarca() {
		return marca;
	}

	public void setMarca(Marca marca) {
		this.marca = marca;
	}

	public JButton getBtnPesquisar() {
		if (btnPesquisar == null) {
			btnPesquisar = new JButton("Pesquisar");
			btnPesquisar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					refreshTable();
				}
			});
			btnPesquisar.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyCode() == 40)
						getTable().requestFocus();
					if (arg0.getKeyCode() == 38)
						getTxtDescricao().requestFocus();
				}
			});
		}
		return btnPesquisar;
	}

	public JButton getBtnSelecionar() {
		if (btnSelecionar == null) {
			btnSelecionar = new JButton("Selecionar");
			btnSelecionar.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 40)
						getBtnSair().requestFocus();
					if (e.getKeyCode() == 38)
						getTable().requestFocus();
				}
			});
			btnSelecionar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					setMarca(getObjectSelecionado());
					if (getMarca() != null)
						dispose();
				}
			});
		}
		return btnSelecionar;
	}

	public JButton getBtnSair() {
		if (btnSair == null) {
			btnSair = new JButton("Sair");
			btnSair.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 40)
						getTxtDescricao().requestFocus();
					if (e.getKeyCode() == 38)
						getBtnSelecionar().requestFocus();
				}
			});
			btnSair.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					dispose();
				}
			});
		}
		return btnSair;
	}
	
protected void refreshTable() {
		
		int cont = getTable().getRowCount() - 1;
		while(cont >= 0) {
			((DefaultTableModel) getTable().getModel()).removeRow(cont);
			cont--;
		}

		
		try {
			
			ArrayList<Marca> marcas = getAction().findByDescricaoLike(getTxtDescricao().getText().trim());
			
			for (Marca marca : marcas) {
				Object objs[] = {marca};
				((DefaultTableModel) getTable().getModel()).addRow(objs);
			}
		} catch (PersistenceExceptionMessage e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

}
